extends Node

var socket = WebSocketPeer.new()

func _ready():
	socket.connect_to_url("ws://120.26.107.184:13140")


func _process(delta):
	socket.poll()
	var state = socket.get_ready_state()
	if state == WebSocketPeer.STATE_OPEN:
		while socket.get_available_packet_count():
			var dataJsonStr = socket.get_packet().get_string_from_utf8()
			print("message received: " + dataJsonStr)
			var data = JSON.parse_string(dataJsonStr)
			NetMessageHandler.call(data.msgType + "_handler", data)
			
	elif state == WebSocketPeer.STATE_CLOSING:
		# Keep polling to achieve proper close.
		pass
	elif state == WebSocketPeer.STATE_CLOSED:
		var code = socket.get_close_code()
		var reason = socket.get_close_reason()
		print("WebSocket closed with code: %d, reason %s. Clean: %s" % [code, reason, code != -1])
		set_process(false) # Stop processing.
		
		
func sendMessage(msgType, data):
	data.msgType = msgType
	socket.send(JSON.stringify(data).to_utf8_buffer())
	
